package com.comtom.soft.thrift.server;

import java.io.UnsupportedEncodingException;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.imps.CuratorFrameworkState;
import org.apache.zookeeper.CreateMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import com.comtom.soft.thrift.exception.ThriftException;
import com.comtom.soft.thrift.service.ThriftServerRegister;

/**
 *  注册服务列表到Zookeeper
 */
public class ThriftServerRegisterZookeeper implements ThriftServerRegister{
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	private CuratorFramework zkClient;
	
	public ThriftServerRegisterZookeeper(){}
	
	public ThriftServerRegisterZookeeper(CuratorFramework zkClient){
		this.zkClient = zkClient;
	}

	public void setZkClient(CuratorFramework zkClient) {
		this.zkClient = zkClient;
	}

	@Override
	public void register(String service, String version, String address,byte[] data) {
		if(zkClient.getState() == CuratorFrameworkState.LATENT){
			zkClient.start();
		}
		String path="/"+service;
		if(StringUtils.isEmpty(version)){
			path=path+"/"+address;
		}else{
			path=path+"/"+version+"/"+address;
		}
		//临时节点
		try {
			zkClient.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(path,data==null?data:new byte[0]);	
		} catch (UnsupportedEncodingException e) {
			logger.error("register service address to zookeeper exception:{}",e);
			throw new ThriftException("register service address to zookeeper exception: address UnsupportedEncodingException", e);
		} catch (Exception e) {
			logger.error("register service address to zookeeper exception:{}",e);
			throw new ThriftException("register service address to zookeeper exception:{}", e);
		}
	}

	@Override
	public void register(String service, String version, String address) {
		register(service, version, address,null);
	}
	
}
